package com.pi.pro.xcmg.am.was.web.cust.controller;


import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.annotation.JsonView;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.service.ICrudService;
import com.pi.framework.core.util.DateUtils;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.framework.core.util.StringUtils;
import com.pi.framework.core.util.csv.CsvExporter;
import com.pi.framework.web.util.CsvView;
import com.pi.pro.xcmg.am.was.edi.infor.dto.req.StorageQueryData;
import com.pi.pro.xcmg.am.was.fac.service.InforCommonWorkService;
import com.pi.pro.xcmg.am.was.fac.service.WasCustomWorkService;
import com.pi.wms.entity.TwiInventoryXwmsDetails;
import com.pi.wms.entity.TwtActPalletizeList;
import com.pi.wms.entity.TwtActWbsTransferList;
import com.pi.wms.service.PalletizeService;
import com.pi.wms.service.WbsTransferListService;
import com.pi.wms.service.XwmsInventoryDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;


@Slf4j
@Controller
@RequestMapping("/inventory/wbstransfer")
public class WbsTransferController extends BaseCrudController<TwtActWbsTransferList, Long> {


    @Autowired
    private WbsTransferListService service;

    @Autowired
    private WasCustomWorkService customWorkService;

    @Override
	protected ICrudService<TwtActWbsTransferList, Long> getCrudService() {
	    return service;
	}

	@Override
	protected String getPrefix() {
		return "wbstransfer";
	}

	@Override
	protected TwtActWbsTransferList newModel(HttpServletRequest request) {
		return new TwtActWbsTransferList();
	}

	@Override
	protected void prepareDatatableConditions(Map<String, Object> query, DataTablesInput input) {
		Long userId = SecurityUtils.getLoginUserId();
		query.put("userId", userId.toString());
		super.prepareDatatableConditions(query, input);
	}


	/**
    @ResponseBody
    @JsonView({DataTablesOutput.View.class})
    @GetMapping({"datatable"})
    @Override
    public DataTablesOutput<TwtActWbsTransferList> datatable(@RequestParam Map<String, Object> q, @Valid DataTablesInput input) {

        DataTablesOutput output=super.datatable(q,input);
        if ((output.getData()==null) && (output.getData().size()==0)){
            return output;
        }

        Map<String, BigDecimal> summ=null;
        Map<String, Object> params=new HashedMap();
        List<TwtActPalletizeList> pals=null;
        String gno="";
        BigDecimal total=null;
        try {
            if ((output.getData()!=null) && (output.getData().size()>0)){
                this.customWorkService.calculateInventoyRecordPalletizeQuantity(output.getData(), true);

            }
        } catch (Exception var5) {
            var5.printStackTrace();
            output = new DataTablesOutput();
            output.setError("加载表格数据发生异常");
        }

        return output;
    }
    **/

    @PostMapping(value = { "/export" })
    public ModelAndView export(@RequestParam Map<String, Object> query, DataTablesInput input) {
        String inputParams = "";
        if (query.get("input")!=null){
            inputParams=query.get("input").toString();
        }
        if (StringUtils.isNotEmpty(inputParams)) {
            input = JSONArray.parseObject(inputParams, DataTablesInput.class);
        }
        input.setLength(-1);
        String ymd = DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HHMMSS);
        final DataTablesInput ins = input;
        CsvExporter<TwtActWbsTransferList> exporter = new CsvExporter<TwtActWbsTransferList>() {
            @Override
            public String[] header() {
                return "物料编码,物料名称,物料WBS,库存数量,单位,供应商,货权方,SAP库位,WMS库位,WMS批,收货日期,查询时间"
                        .split(",");
            }

            @Override
            public Collection<TwtActWbsTransferList> nextList(int pageSize, int page) {
                ins.setLength(pageSize);
                ins.setStart(page * pageSize);
                Pageable pageable = PageRequest.of(page, pageSize);
                Page<TwtActWbsTransferList> out = service.findAll(query,pageable);
                return out == null ? null : out.getContent();
            }

            @Override
            public Collection<String> toText(TwtActWbsTransferList d) {
                List<String> item = new ArrayList<String>();
                String recvtime="";

                /**
                item.add(d.getMaterialCode()!= null ? d.getMaterialCode() : "");
                item.add(d.getMaterialName()!= null ? d.getMaterialName() : "");
                item.add(d.getWbsNum()!= null ? d.getWbsNum() : "");
                item.add(d.getStorageQty()!= null ? d.getStorageQty() .stripTrailingZeros().toPlainString(): "");
                item.add(d.getUomCode()!= null ? d.getUomCode() : "");
                item.add(d.getSupplierCode()!= null ? d.getSupplierCode() : "");
                item.add(d.getCustomerCode()!= null ? d.getCustomerCode() : "");
                item.add(d.getStorageLocCode()!= null ? d.getStorageLocCode() : "");
                item.add(d.getXwmsLocCode()!= null ? d.getXwmsLocCode() : "");
                item.add(d.getXwmsLotNumber()!= null ? d.getXwmsLotNumber() : "");

                recvtime="";
                if (!StringUtils.isNullOrBlank(d.getXwmsReceiveTime())){
                    recvtime=d.getXwmsReceiveTime();
                }
                if (recvtime.length()>10){
                    recvtime=recvtime.substring(0, 10);
                }
                 **/
                item.add(recvtime);
                //item.add(DateUtils.format(d.getXwmsReceiveTime(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
                item.add(DateUtils.format(d.getCreatedDate(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
                return item;
            }
        };
        return new ModelAndView(new CsvView(exporter, "库存转批记录_" + ymd));
    }


    protected String redirect(String relativeUrl) {
        if(!StringUtils.isNullOrBlank(relativeUrl) && !relativeUrl.startsWith("/")) {
            relativeUrl = "/" + relativeUrl;
        }
        return "redirect:" + this.referUrl() + relativeUrl;
    }

    protected String root(String relativeUrl) {
        if(!StringUtils.isNullOrBlank(relativeUrl) && !relativeUrl.startsWith("/")) {
            relativeUrl = "/" + relativeUrl;
        }
        return this.referUrl() + relativeUrl;
    }

    private String referUrl(){
        return "/inventory/wbstransfer/";
    }

}
